<template>
  <div class="case">
    <na-table :datas.sync="tableData" :searchObj.sync="search" @newAdd="isAddCus = true" @updateDatas="getAllLists">
    </na-table>
    <!-- 新建客户   -->
    <el-dialog title="新建客户" :visible.sync="isAddCus" :close-on-click-modal="false" custom-class="comDialog" width="40%"
      @close="closeDialog">
      <div class="dialogDody">
        <el-form ref="customerForm" :model="customerForm" :rules="rules" label-width="90px" class="dialogForm">
          <el-form-item label="客户编号">
            <el-input v-model="customerForm.customerCode" placeholder="系统自动生成" size="mini" disabled />
          </el-form-item>
          <el-form-item label="客户名称" prop="customerName">
            <el-input v-model="customerForm.customerName" placeholder="请输入客户名称" size="mini" />
          </el-form-item>
          <el-form-item label="结算方式" prop="settlementWay">
            <el-select
                        filterable v-model="customerForm.settlementWay" filterable placeholder="请选择结算方式" size="mini">
              <el-option label="现结" value="1" />
              <el-option label="月结" value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="销售代表" prop="belongToSalesmanName">
            <div class="flex flex_center">
              <div class="flex1">
                <el-input v-model="customerForm.belongToSalesmanName" placeholder="选择人员" size="mini" disabled />
              </div>
              <div class="ml10 btnPer">
                <el-button type="primary" size="mini" icon="el-icon-user" @click="isperShow = true">选择人员</el-button>
              </div>
            </div>
          </el-form-item>
          <el-form-item label="联系人">
            <el-input v-model="customerForm.contactPerson" placeholder="请输入联系人" size="mini" />
          </el-form-item>
          <el-form-item label="联系电话">
            <el-input v-model="customerForm.contactMobile" placeholder="请输入联系电话" size="mini" />
          </el-form-item>
          <el-form-item label="客户地址">
            <el-cascader v-model="customerForm.areas" size="mini" :options="address"
              :props="{ label: 'areaName', value: 'areaCode' }" @change="areaChange" />
          </el-form-item>
          <el-form-item label="" class="mt5">
            <el-input v-model="customerForm.customerAddress" type="textarea" placeholder="请输入内容" size="mini" />
          </el-form-item>
          <el-form-item label="备注" class="mt12">
            <el-input v-model="customerForm.customerRemark" type="textarea" placeholder="请输入内容" size="mini" />
          </el-form-item>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="isAddCus = false">取 消</el-button>
        <el-button :loading="addLoading" :disabled="addLoading" element-loading-spinner="el-icon-loading" type="primary"
          size="mini" @click="addSave">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 人员寻找弹框   -->
    <per-redio-dialog :per-visible.sync="isperShow" @getEmployee="getEmployee" />
  </div>
</template>
<script>
  import perRedioDialog from "@/components/perDialogRedio";
  import screec from "@/components/screen";
  import naTable from "@/components/naTable";
  import {
    arraySort
  } from "@/utils";

  export default {
    name: "CustomerSummary",
    components: {
      naTable,
      perRedioDialog,
      screec
    },
    data() {
      return {
        isperShow: false, // 选择人员弹框是否打开
        addLoading: false, // 新建客户保存加载效果
        isAddCus: false, // 新建客户弹框是否打开
        searchLoading: false, // 客户汇总列表加载效果
        search: {
          QueryDataBaseFiled: '',
          pageIndex: 1,
          pageSize: 30,
          settlementWay: 0,
          belongToSalesman: "",
          likeWords: "",
        },
        dataLists: [], // 客户汇总列表
        total: 0,
        tableHeight: null, // 表格最大高度
        tableHead: [], // 表头
        // 表格操作按钮
        // operations: [
        //   [{ text: "查看", key: "see" }],
        //   [{ text: "启用", key: "enable" }],
        //   [{ text: "删除", key: "delete" }],
        // ],
        address: [], // 地区集合
        customerForm: {
          customerCode: "系统自动生成",
          customerName: "",
          settlementWay: "",
          belongToSalesman: "",
          belongToSalesmanName: "",
          contactPerson: "",
          contactMobile: "",
          areas: [],
          province: "",
          city: "",
          country: "",
          customerAddress: "",
          customerRemark: "",
        },
        isEnabled: null,
        rules: {
          customerName: [{
            required: true,
            message: "客户名称必填",
            trigger: ["change", "blur"],
          }, ],
          settlementWay: [{
            required: true,
            message: "请选择结算方式",
            trigger: "change"
          }, ],
          belongToSalesmanName: [{
            required: true,
            message: "请选择销售代表",
            trigger: "change"
          }, ],
        },

        tableData: {
          headId: 'head', //表头列显隐组件所需ID-避免多个页面id重复问题
          tableId: 'customerID', //表格列表key,也就是一条数据的唯一标识
          senior: false, //高级搜索是否显示
          disableWord: 'customerStateName', //是否禁用显示的字段
          disableStatus: '正常', //判断未禁用的状态值
          addPermission: 'MenuCode1-4-1', //新建按钮权限
          voidWord: '', //需要查询作废的字段
          //表格按钮
          operationBtn: [{
              title: '查看', //按钮名称
              methodsName: 'lookCustomer', //按钮绑定方法的字段
              permission: ''
            },
            {
              title: '禁用',
              methodsName: 'setSupplierSate',
              permission: 'MenuCode1-4-2'
            },
            {
              title: '删除',
              methodsName: 'deleteCustomer',
              permission: 'MenuCode1-4-3'
            },
          ],
          //表格内容
          tbody: [],
          //表格表头
          thead: [],
        }
      };
    },
    created() {
      // 获取仓库管理列表表格表头
      this.getTableHead();
      // 地区联动数据
      this.getArea();
    },
    mounted() {},
    methods: {
      // 设置客户状态
      setSupplierSate(row) {
        row.customerState === 1 ?
          (this.isEnabled = false) :
          (this.isEnabled = true);
        const parmas = {
          customerID: row.customerID,
          isEnabled: this.isEnabled,
        };
        this.$confirm("确定启用/禁用, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.$api.business.DisableorEnableCustomer(parmas).then(() => {
            this.getAllLists();
            this.$message({
              message: "设置成功",
              type: "success",
            });
          });
        });
      },
      // 删除客户
      deleteCustomer(row) {
        const parmas = {
          customerID: row.customerID,
        };
        this.$confirm("确定删除当前客户, 是否继续?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }).then(() => {
          this.$api.business.DeleteCustomer(parmas).then(() => {
            this.getAllLists();
            this.$message({
              message: "删除成功",
              type: "success",
            });
          });
        });
      },
      // 新建客户保存
      addSave() {
        const parmas = this.customerForm;
        this.$refs.customerForm.validate((valid) => {
          if (valid) {
            this.addLoading = true;
            this.$api.business
              .CreateNewCustomer(parmas)
              .then(() => {
                this.addLoading = false;
                this.isAddCus = false;
                this.getAllLists();
                this.$message({
                  message: "新增成功",
                  type: "success",
                });
              })
              .catch(() => {
                this.addLoading = false;
              });
          }
        });
      },
      // 合计方法
      getSummaries(param) {
        const {
          columns,
          data
        } = param;
        const sums = [];
        columns.forEach((column, index) => {
          if (index === 0) {
            sums[index] = "合计";
            return;
          }
          if (
            column.property === "orderSumCount" ||
            column.property === "consumeAmount" ||
            column.property === "payedMoney" ||
            column.property === "waitPayMoney"
          ) {
            const values = data.map((item) => Number(item[column.property]));
            if (!values.every((value) => isNaN(value))) {
              sums[index] = values.reduce((prev, curr) => {
                const value = Number(curr);
                if (!isNaN(value)) {
                  return prev + curr;
                } else {
                  return prev;
                }
              }, 0);
              sums[index] = Number((sums[index]++).toFixed(2));
            } else {
              sums[index] = " ";
            }
          }
        });
        return sums;
      },
      lookCustomer(row) {
        // 查看
        this.$router.push({
          path: "/business/customerInfo", // 跳转的路径
          query: {
            customerID: row.customerID,
            customerCode: row.customerCode,
          },
        });
      },
      // 得到仓库管理员
      getEmployee(val) {
        this.customerForm.belongToSalesman = val.employeeCode;
        this.customerForm.belongToSalesmanName = val.employeeName;
      },
      // 选择地址
      areaChange(val) {
        this.customerForm.province = val ? val[0] : "";
        this.customerForm.city = val ? val[1] : "";
        this.customerForm.country = val ? val[2] : "";
      },
      // 地区联动数据
      getArea() {
        this.$api.common.GetTreeAreaDataList().then((res) => {
          this.address = res;
        });
      },
      // 得到客户汇总所有数据列表
      getAllLists() {
        const parmas = this.search;
        this.searchLoading = true;
        this.$api.business
          .QueryPageCustomerList(parmas)
          .then((res) => {
            this.tableData.tbody = res.list;
            this.search.total = res.totalCount;
            this.searchLoading = false;
          })
          .catch(() => {
            this.searchLoading = false;
          });
      },
      // 获取仓库管理列表表格表头
      getTableHead() {
        const parmas = {
          tableCode: this.$config.customerlist,
        };
        this.$api.common.getAllTableHead(parmas).then((res) => {
          res.sort(arraySort("columnSort"));
          this.tableData.thead = res;
          // 得到客户汇总所有数据列表
          this.getAllLists();
        });
      },
      // 新建客户弹框关闭事件
      closeDialog() {
        if (this.$refs.customerForm) {
          this.$refs.customerForm.resetFields();
        }
        this.customerForm = this.$options.data().customerForm;
      },
    },
  };

</script>
<style lang="scss" scoped>
</style>
